<script setup>
import { vDraggable } from 'vue-draggable-plus'
import { vFocus } from '@/directives'

// DEMO

const tableRef = useTemplateRef('tableRef')

const heads = ref([
  { label: '姓名', key: 'name', width: '' },
  { label: '年龄', key: 'age', width: '' },
  { label: '性别', key: 'sex', width: '' },
])
const tables = ref([
  { id: '1', name: 'lafen1', age: 18, sex: 'male' },
  { id: '2', name: 'lafen2', age: 20, sex: 'male' },
  { id: '3', name: 'lafen3', age: 28, sex: 'male' },
])
const foots = ref([])

const attrs = ref({
  border: 'border',
  width: '100%',
  className: ['border-collapse'],
})

const styles = ref({})

let tabIndex = 0
const getTabIndex = () => {
  return tabIndex++
}

const currentItem = ref({})

const handleClickCurrentHead = item => {
  currentItem.value = item
  console.log('click current', item)
}
const currentKey = ref('')
const handleClickCurrentCell = (item, key) => {
  currentItem.value = item
  currentKey.value = key
  console.log('click current cell', item, key)
}
const getActiveClassHead = item => {
  return item.key === currentItem.value.key ? 'activeClass' : ''
}
const isEditCell = (item, key) => {
  return item.id === currentItem.value.id && currentKey.value === key
}
const getActiveClassCell = (item, key) => {
  return isEditCell(item, key) ? 'activeClass' : ''
}

const getItemWidthHead = item => {
  return (item.width || 100 / heads.value.length) + '%'
}

defineOptions({ name: 'RenderTable' })
</script>

<template>
  <table ref="tableRef" v-bind="attrs">
    <caption>
      表格说明
    </caption>
    <thead>
      <tr v-draggable="[heads, { animation: 150 }]">
        <th
          v-for="(item, index) of heads"
          :key="item.key"
          :tabindex="getTabIndex()"
          :class="getActiveClassHead(item)"
          :width="getItemWidthHead(item)"
          @click="handleClickCurrentHead(item)"
          @focus="handleClickCurrentHead(item)"
        >
          {{ item.label }}
        </th>
      </tr>
    </thead>
    <tbody v-draggable="[tables, { animation: 150 }]">
      <tr v-for="(item, index) of tables" :key="item.id">
        <td
          v-for="(it, i) of heads"
          :key="it.key"
          :class="getActiveClassCell(item, it.key)"
          @click="handleClickCurrentCell(item, it.key)"
          @focus="handleClickCurrentCell(item, it.key)"
        >
          <input
            v-focus
            v-if="isEditCell(item, it.key)"
            v-model="item[it.key]"
            :tabindex="getTabIndex()"
          />
          <div v-else>{{ item[it.key] }}</div>
        </td>
      </tr>
    </tbody>
    <tfoot>
      <tr>
        <td>表尾1</td>
        <td>表尾2</td>
      </tr>
    </tfoot>
  </table>
</template>
